
from flask import request
from utils.randomUtils import generate_random_token, generate_random_by_time
import threading
from .baseGraphNode import  *
from .httpGraphNode import HttpGraphNode
from .sessionInfo import SessionInfo
from ..execute.baseExeHis import BaseExeHis

class MessageHistoryGraphNode(BaseGraphNode):
    def __init__(self, id:str, data:dict, graphNodeManager, random_key:str):
        super().__init__(id, data, graphNodeManager, random_key)
        self.database = data['data'].get('database', 'default')
        if self.graphNodeManager.http_node is not None:
            self.full_url = self.graphNodeManager.http_node.full_url
        else:
            self.graphNodeManager.http_node = HttpGraphNode(generate_random_by_time(), self.data, self.graphNodeManager, self.random_key)
            self.full_url = self.graphNodeManager.http_node.full_url
        self._ws_token = self.full_url
        self.running = False


    def execute(self, session_info: SessionInfo=None, exe_his: BaseExeHis=None, trigger=None, running_id=None, **kwargs): # kwargs={'type':'text or image', 'role':'user or assistant'}

        if kwargs is None:
            kwargs = {}
        if 'type' not in kwargs:
            kwargs['type'] = 'text'
        
        if session_info.id not in self.graphNodeManager.project.databases:
            self.graphNodeManager.project.databases[session_info.id] = {}
        if self.database not in self.graphNodeManager.project.databases[session_info.id]:
            self.graphNodeManager.project.databases[session_info.id][self.database] = {}
        if 'msgs' not in self.graphNodeManager.project.databases[session_info.id][self.database]:
            self.graphNodeManager.project.databases[session_info.id][self.database]['msgs'] = []
            self.graphNodeManager.project.databases[session_info.id][self.database]['msgs'].append([])

        if kwargs['type'] == 'text':
            if 'in-msg' in self.dict['in']: # {'nodeId': sourceID, 'handle': sourceHandle}
                inFrom = self.dict['in']['in-msg']
                prenode =self.graphNodeManager.nodesByIdDict[inFrom['nodeId']]
                inMsg = prenode.get_newest_output_in_session(session_info, inFrom['handle'])
                self.graphNodeManager.project.databases[session_info.id][self.database]['msgs'][-1].append(Msg(content=inMsg, role=kwargs['role'], msg_type='text'))

        elif kwargs['type'] == 'image':
            if 'in-image' in self.dict['in']:
                inFrom = self.dict['in']['in-image']
                prenode =self.graphNodeManager.nodesByIdDict[inFrom['nodeId']]
                inImg = prenode.get_newest_output_in_session(session_info, inFrom['handle'])
                self.graphNodeManager.project.databases[session_info.id][self.database]['msgs'][-1].append(Msg(content=inImg, role=kwargs['role'], msg_type='image'))


    def get_newest_output_in_session(self, session_info: SessionInfo, handle: str) -> list[dict]:
        if session_info.id not in self.graphNodeManager.project.databases: return []
        if self.database not in self.graphNodeManager.project.databases[session_info.id]: return []
        if 'msgs' not in self.graphNodeManager.project.databases[session_info.id][self.database]: return []
        if len(self.graphNodeManager.project.databases[session_info.id][self.database]['msgs']) == 0: return []
        return self.graphNodeManager.project.databases[session_info.id][self.database]['msgs'][-1]